package com.sq.util;

public class UnicodeUtil {

    /*
     * N\u4f60\u597d 转成 N你好
     */
    public static String decode(String str) {
        StringBuilder result = new StringBuilder();
        char[] arr = str.toCharArray();
        boolean found = false;
        StringBuilder t = new StringBuilder();
        for (int i = 0, len = arr.length; i < len;) {
            char c = arr[i];
            if ('\\' == c) {
                if (t.length() > 0) {
                    char letter = (char) ByteUtil.toInt(t.toString()); // 16进制parse整形字符串。
                    result.append(letter);
                    found = false;
                    t = new StringBuilder();
                }
                int j = i + 1;
                if (j < len && arr[j] == 'u') {
                    found = true;
                    i += 2;
                } else {
                    found = false;
                    i++;
                }
            } else if (found) {
                t.append(c);
                i++;
            } else {
                result.append(c);
                i++;
            }
        }
        if (t.length() > 0) {
            char letter = (char) ByteUtil.toInt(t.toString()); // 16进制parse整形字符串。
            result.append(letter);
        }
        return result.toString();
    }

    /*
     * N你好 转成 \u004e\u4f60\u597d
     */
    public static String encode(String str) {
        char[] arr = str.toCharArray();
        StringBuilder result = new StringBuilder();
        for (char c : arr) {
            result.append('\\').append('u');
            result.append(ByteUtil.toHexString(ByteUtil.shortToBytes((short) c)));
        }
        return result.toString();
    }
}
